﻿/*
 * 	===如果两个值的类型不同，直接返回false;==会自动类型转换，判断不严谨
 *	typeof用来检测给定变量的数据类型，返回对应数据类型的字符串
 * */
//歌曲列表
var Song = function(o) {
	this.setting = (typeof o === 'object') ? o : {};
	
	//用于标示模块:新歌/排行/歌手
	this.target = this.setting.target || 'newSong';
	//模块类型,目前只实现了类型1，只有查询歌曲的功能
	this.type = typeof this.setting.type === 'number' ? this.setting.type
			: parseInt(this.setting.type);
	//首次显示数据条数
	this.firstCount = typeof this.setting.firstCount === 'number' ? this.setting.firstCount
			: parseInt(this.setting.firstCount);
	//点击更多之后显示的数据条数
	this.count = typeof this.setting.count === 'number' ? this.setting.count
			: parseInt(this.setting.count);
	this.content = $("#content");
	// 初始化
	this.init();
}

Song.prototype = {
	init : function() {
		// 列表初始化
		this.content.html("");
		// 堆栈指针初始化
		this.stack = 0;
		// 图片路径
		this.imgPath = 'static/data/image/';
		// 定时器
		this.timer = null;
		// 测试JSON数据（可以替换为AJAX请求返回值）
		this.testJson = {
			list : [
				{
				    "id" : 1,
				    "fileName" : "寂寞沙洲冷.mp3",
				    "imageName" : "ywaq.jpg",
				    "songName" : "寂寞沙洲冷",
				    "singer" : "小刚",
				    "album" : "星空下的传说",
				    "releaseDate" : "2006-11-11 00:00:00",
				    "inputTime" : "2016-10-11 15:21:00"
				  }, {
				    "id" : 2,
				    "fileName" : "大王叫我来巡山.mp3",
				    "imageName" : "ywaq.jpg",
				    "songName" : "大王叫我来巡山2",
				    "singer" : "贾乃亮",
				    "album" : "万万没想到",
				    "releaseDate" : "2015-11-11 00:00:00",
				    "inputTime" : "2015-11-11 09:00:00"
				  }, {
				    "id" : 3,
				    "fileName" : "大王叫我来巡山.mp3",
				    "imageName" : "ywaq.jpg",
				    "songName" : "大王叫我来巡山3",
				    "singer" : "贾乃亮,贾云馨",
				    "album" : "万万没想到",
				    "releaseDate" : "2015-11-11 00:00:00",
				    "inputTime" : "2015-11-11 09:00:00"
				  }, {
				    "id" : 4,
				    "fileName" : "大王叫我来巡山.mp3",
				    "imageName" : "ywaq.jpg",
				    "songName" : "大王叫我来巡山4",
				    "singer" : "贾乃亮,贾云馨",
				    "album" : "万万没想到",
				    "releaseDate" : "2015-11-11 00:00:00",
				    "inputTime" : "2015-11-11 09:00:00"
				    
				  }, {
				    "id" : 5,
				    "fileName" : "大王叫我来巡山.mp3",
				    "imageName" : "ywaq.jpg",
				    "songName" : "大王叫我来巡山5",
				    "singer" : "贾乃亮,贾云馨",
				    "album" : "万万没想到",
				    "releaseDate" : "2015-11-11 00:00:00",
				    "inputTime" : "2015-11-11 09:00:00"
				  } , {
				    "id" : 6,
				    "fileName" : "大王叫我来巡山.mp3",
				    "imageName" : "ywaq.jpg",
				    "songName" : "大王叫我来巡山4",
				    "singer" : "贾乃亮,贾云馨",
				    "album" : "万万没想到",
				    "releaseDate" : "2015-11-11 00:00:00",
				    "inputTime" : "2015-11-11 09:00:00"
				    
				  }, {
				    "id" : 7,
				    "fileName" : "大王叫我来巡山.mp3",
				    "imageName" : "ywaq.jpg",
				    "songName" : "大王叫我来巡山4",
				    "singer" : "贾乃亮,贾云馨",
				    "album" : "万万没想到",
				    "releaseDate" : "2015-11-11 00:00:00",
				    "inputTime" : "2015-11-11 09:00:00"
				    
				  }, {
				    "id" : 8,
				    "fileName" : "大王叫我来巡山.mp3",
				    "imageName" : "ywaq.jpg",
				    "songName" : "大王叫我来巡山4",
				    "singer" : "贾乃亮,贾云馨",
				    "album" : "万万没想到",
				    "releaseDate" : "2015-11-11 00:00:00",
				    "inputTime" : "2015-11-11 09:00:00"
				    
				  }, {
				    "id" : 9,
				    "fileName" : "大王叫我来巡山.mp3",
				    "imageName" : "ywaq.jpg",
				    "songName" : "大王叫我来巡山4",
				    "singer" : "贾乃亮,贾云馨",
				    "album" : "万万没想到",
				    "releaseDate" : "2015-11-11 00:00:00",
				    "inputTime" : "2015-11-11 09:00:00"
				    
				  }, {
				    "id" : 10,
				    "fileName" : "大王叫我来巡山.mp3",
				    "imageName" : "ywaq.jpg",
				    "songName" : "大王叫我来巡山4",
				    "singer" : "贾乃亮,贾云馨",
				    "album" : "万万没想到",
				    "releaseDate" : "2015-11-11 00:00:00",
				    "inputTime" : "2015-11-11 09:00:00"
				    
				  },
				  {
					    "id" : 11,
					    "fileName" : "大王叫我来巡山.mp3",
					    "imageName" : "ywaq.jpg",
					    "songName" : "发如雪",
					    "singer" : "周杰伦",
					    "album" : "发如雪",
					    "releaseDate" : "2015-11-11 00:00:00",
					    "inputTime" : "2015-11-11 09:00:00"
					    
					  }]
		};
		this.songJson = {};
		this.userSongJson = {};
		this.createList(true);
		//this.buildLoveTag();
		this.addHandle();
	},

	// 创建内容列表
	createList : function(boolen) {
		// boolen:true/false确定是否初次载入，
		this.ulNode = document.createElement("ul");
		this.ulNode.id = this.target + "list";
		this.content.append(this.ulNode);
		this.ulTarget = $("#" + this.ulNode.id);
		this.createMore();
		this.loadList(boolen);
	},

	// 创建更多按钮
	createMore : function() {
		this.moreNode = document.createElement("div");
		this.moreNode.className = 'm';
		this.moreNode.innerHTML = '更多';
		this.moreNode.id = this.target + 'more';
		this.moreTarget = $("#" + this.moreNode.id);
	},

	
	// 加载列表
	loadList : function(boolen) {
		var _this = this;
		var oLength;
			if (boolen) {
				//获取已登录用户的收藏歌曲
				 $.ajax({
					 url : url.MY_SONG,
					 type : "POST",
					 async : false,
					 success : function(data) {
						 _this.userSongJson = data.list;
					 }
				 });
				  //如果是点击查看我的歌曲
				  if(this.target == "mySong") {
					  _this.songJson = _this.userSongJson;
					//未认证或没有记住我,需要登录才能查看我的歌曲
					  if(_this.songJson == undefined) {
						  layer.msg("请先登录", {icon: 0, time: 1000},function() {
							  window.location.href = url.LOGIN;
								return;
						  })
						}
				  } else {
					  $.ajax({
						 url : url.SONG_LIST,
						 type : "POST",
						 async: false,
						 success : function(data) {
							 _this.songJson = data.list;
							// _this.songJson = _this.testJson.list;
						   }
						 });
				   }
			
				oLength = _this.songJson.length > _this.firstCount ? _this.firstCount
						: _this.songJson.length;
			   _this.showCount(oLength);
			   
			} else {
				oLength = (this.songJson.length - this.stack) > this.count ? this.count
						: (this.songJson.length - this.stack);
				this.showCount(oLength);
			}
			
	},
	
	showCount : function(oLength){
		if (oLength <= 0) {
			this.moreTarget.text("这是最后一页了！");
		}
		;

		if (!this.moreTarget[0]) {
			this.content.append(this.moreNode);
		}
		;

		for (var i = 0; i < oLength; i++) {
			this.showView(this.songJson);
		}
	},

	//把从后台拿到的json数据展现到页面
	showView : function(oList) {
		switch (this.type) {
		// 根据不同的模块 定制不同的数据展示形式
		case 1:
			this.ulTarget.append('<li ondblclick="myControl.rePlay(this, '
					+ this.stack +','+ oList[this.stack].id +')">' 
					+ '<div title="播放" onclick="myControl.selectList(this,'
					+ this.stack + ','+ oList[this.stack].id +')" class="frmPlay"></div>' 
					+ '<div onclick="myControl.selectHobby('+ oList[this.stack].id + ')" '
					+ 'class="nolove '+ oList[this.stack].id +'" title="收藏"><i></i></div>'
					+ '<span style="display:none;" class="musicData" pic="'
					+ oList[this.stack].imageName + '" title="'
					+ oList[this.stack].songName + '" value="'
					+ oList[this.stack].fileName + '" lyricName="'
					+ oList[this.stack].lyricName + '" songId="'
					+ oList[this.stack].id +'"></span>'
					+ '<div class="l"><img class="picStyle" src="'
					+ this.imgPath + oList[this.stack].imageName + '"/></div>'
					+ '<div class="textBox">' + oList[this.stack].songName
					+ '<p>' + oList[this.stack].singer + '-'
					+ oList[this.stack].album + '</p></div>' + '</li>');
			break;
		case 2:
			this.content[0].innerHTML = '此模块建设中...';
			break;
		default:
			alert("该模块出错！");
		}
		if(this.userSongJson != undefined)
			this.buildLoveTag(oList[this.stack].id, this.stack, this.ulTarget);
		this.stack += 1;
	},
	
	//构建爱心图标
	buildLoveTag : function(id, stack, _ulTarget) {
		
		var songDiv = _ulTarget.find("li:eq("+ stack +")").find(".nolove");
		$.each(this.userSongJson, function(index, item){
			if(item.id == id) {
				songDiv.removeClass("nolove")
					   .addClass("love")
					   .attr("title","取消收藏");
			}
		});
		//同时判断当前歌曲是否是正在播放的歌曲,是则把"frmPlay"换为"frmPause"
		if(myControl.prevSongId == id) {
			var frmDiv = _ulTarget.find("li:eq("+ stack +")").find(".frmPlay");
			frmDiv.removeClass("frmPlay").addClass("frmPause");
		}
	},

	// 绑定事件
	addHandle : function() {
		this.moreNode.setAttribute("onclick",("javascript:module."+this.target+".createList(false);"));
	}

}
// 播放器控制面板
var Control = function(o) {
	this.setting = (typeof o === 'object') ? o : {};
	this.audio = this.setting.audio;
	this.progressWrap = this.setting.progressWrap;
	this.playModeNode = this.setting.playModeNode;
	this.playBtn = this.setting.playBtn;
	this.playTitle = this.setting.playTitle;
	this.singerHead = this.setting.singerHead;
	this.progress = this.setting.progress;
	this.oWinObj = this.setting.oWinObj;
	this.allTimeNode = this.setting.allTimeNode;
	this.currentTimeNode = this.setting.currentTimeNode;
	this.path = 'static/data/media/'; // 歌曲路径（相对于html）
	this.imgPath = 'static/data/image/'; // 图片路径（相对于html）
	this.init();
}

Control.prototype = {
	// 初始化
	init : function() {
		// 播放控制
		this.start = true;
		
		this.isFirst = true;
		
		this.prevSongId = 0;
		// 定时器
		this.timer = null;
		this.audio.src = null;
		// 可选播放模式
		this.ModeData = [ {
			mode : 'default',
			text : '顺序播放模式'
		}, {
			mode : 'random',
			text : '随机播放模式'
		}, {
			mode : 'single',
			text : '单曲循环模式'
		} ];
		// 默认播放模式
		this.ModeIndex = 0;
		this.playMode = this.ModeData[this.ModeIndex].mode;
	},

	// 选择歌曲列表
	selectList : function(_this, stack, id) {
		var allow = true;
		var index = null;
		this.oLi = _this.parentNode;
		this.oUl = _this.parentNode.parentNode;
		if (index == stack) {
			allow = false;
		}
		index = stack;
		//第一次播放
		if(this.prevSongId == 0) {
			this.isFirst = true;
			this.start = true;
		//如果当前点击的歌曲不是正在播放的歌曲,则重新加载歌曲播放
		}else if(this.prevSongId != id) {
			this.isFirst = true;
			this.start = true;
		}
		
		//this.prevSongId = id;
		//新播放歌曲
		if(this.isFirst && allow) {
			this.loadMusic();
			this.showLoveTag(id);
			this.isFirst = false;
			//增加播放次数
			increaseTimes(id);
		}
		if (allow) {
			if(this.start) {
				this.goPlay();
			}else{
				this.goPause();
			}
			
		} else {
			this.goPause();
		}
		
		function increaseTimes(id) {
			$.post(url.INCREASE, {"id":id});
		}
	},
	
	//重新播放
	rePlay : function(_this, stack, id) {
		
		var playDiv = $(_this).find("div:eq(0)")[0];
		this.isFirst = true;
		this.start = true;
		this.selectList(playDiv, stack, id);
	},
	
	//收藏 或 取消收藏歌曲
	selectHobby : function(id) {
		
		var hobbyTag = 0;
		if($("."+id).is('.nolove')) {
			hobbyTag = 1;
		}
		var param = {"id":id, "hobbyTag":hobbyTag};
		$.ajax({
  		  type: "POST",
  		  url: window.url.SAVE_SONG,
  		  data: param,
  		  async: false,
  		  success: function(result) {
  			if(result.code == undefined) {
				layer.msg("请先登录",{icon: 0, time: 1000},function() {
					  window.location.href = url.LOGIN;
						return;
				  });
			}
			if(result.code == 1) {
				if(hobbyTag == 0) {
					hobbyWitch($("."+id),"love", "nolove", "收藏");
					layer.msg("已取消", {icon:1, time: 1000});
				}else if(hobbyTag == 1) {
					hobbyWitch($("."+id),"nolove", "love", "取消收藏");
					layer.msg("已收藏",{icon:1, time: 1000});
				}
			}else if(result.code == 0) {
				layer.msg("操作失败", {icon: 1, time:1000, shift: 3});
			}
  		  }
  	  });
		//重新构建爱心
		function hobbyWitch(obj, removeClass, addClass, title) {
			obj.removeClass(removeClass);
			obj.addClass(addClass);
			obj.attr("title",title);
		}
		return hobbyTag;
	},
	
	// 上一首
	prev : function() {
		if (this.oLi.previousSibling != null) {
			this.oLi = this.oLi.previousSibling;
			this.loadMusic();
		} else {
			this.oWindow("已经是第一首了哦！");
		}
		this.goPlay();
	},

	// 主控
	mainControl : function() {
		if (this.start) {
			this.goPlay();
		} else {
			this.goPause();
		}
	},

	// 下一首
	next : function() {
		if (this.oLi.nextSibling != null) {
			this.oLi = this.oLi.nextSibling;
			this.loadMusic();
		} else {
			this.oWindow("已经是最后一首了哦！");
		}
		this.goPlay();
	},

	// 播放模式选择
	selectMode : function() {
		this.ModeIndex = (this.ModeIndex < (this.ModeData.length - 1)) ? (this.ModeIndex + 1)
				: 0;
		this.playMode = this.ModeData[this.ModeIndex].mode;
		this.oWindow(this.ModeData[this.ModeIndex].text);
		this.playModeNode.attr("class", "mode-" + this.playMode);
	},

	// 播放进度选择
	selectTime : function(event) {
		var moveTo = event.pageX - this.progressWrap.offset().left;
		this.audio.currentTime = moveTo
				/ parseInt(this.progressWrap.css("width"))
				* this.audio.duration;
		this.progress.css("width", moveTo + "px");
	},

	// 自动播放
	autoPlay : function() {
		// 监听歌曲结束
		var that = this;
		this.audio
				.addEventListener(
						'ended',
						function() {
							if (typeof that.playMode === 'string') { // 播放模式判断
								switch (that.playMode) {
								case 'default':
									that.oLi = (that.oLi.nextSibling != null) ? that.oLi.nextSibling
											: that.oUl.childNodes[0];
									break;
								case 'random':
									that.oLi = that.oUl.childNodes[Math
											.round(Math.random()
													* (that.oUl.childNodes.length - 1))];
									break;
								case 'single':
									;
								default:
									;
								}
								that.loadMusic();
								that.goPlay();
							} else {
								that.oWindow("循环类型不符!");
							}
						}, false);
	},

	// 加载要播放的歌曲
	loadMusic : function() {
		this.currentTimeNode.html("00:00");
		$obj = $(this.oLi);
		var song = $obj.find(".musicData").attr("value");
		var pic = $obj.find(".musicData").attr("pic");
		var title = $obj.find(".musicData").attr("title");
		var lyricName = $obj.find(".musicData").attr("lyricName");
		this.prevSongId = $obj.find(".musicData").attr("songId");
		this.singerHead.attr("src", this.imgPath + pic);
		this.audio.src = this.path + song;
		//加载歌词
		getReady(lyricName);
		console.log(song.toString());
		this.playTitle.html(title);
	},

	// 判断当前是否歌曲列表
	songReady : function() {
		if (!this.audio.src) {
			this.oWindow("请先选择歌曲！")
			return false;
		} else {
			return true;
		}
	},

	// 转换为时间格式
	timeDispose : function(number) {
		var minute = parseInt(number / 60);
		var second = parseInt(number % 60);
		minute = minute >= 10 ? minute : "0" + minute;
		second = second >= 10 ? second : "0" + second;
		return minute + ":" + second;
	},

	// 自定义提示框
	oWindow : function(oText) {
		this.oWinObj.show();
		this.oWinObj.html(oText);
		var doc = document.documentElement;
		var oWinX = (doc.clientWidth - this.oWinObj[0].offsetWidth) / 2;
		var oWinY = (doc.clientHeight - this.oWinObj[0].offsetHeight - 50) / 2;
		this.oWinObj.css('left', oWinX + 'px');
		this.oWinObj.css('top', oWinY + 'px');
		var _this = this;
		setTimeout(function() {
			_this.oWinObj.hide();
		}, 1000)
	},

	// 播放时间
	oTime : function() {
		if (this.audio.readyState >= 4) {
			var currentProgress = Math.round(this.audio.currentTime
					/ this.audio.duration
					* parseInt(this.progressWrap.css("width")));
			this.progress.css("width", currentProgress + "px");
			this.allTimeNode.html(this.timeDispose(this.audio.duration));
			this.currentTimeNode.html(this.timeDispose(this.audio.currentTime));
		}
	},
	
	//点击播放歌曲,同时显示播放进度条右边的爱心
	showLoveTag : function(id) {
		var hoppyDiv = $("."+id)[0];
		var classAttr = $(hoppyDiv).attr("class");
		//alert("classAttr: " + classAttr);
		var title = $(hoppyDiv).attr("title");
		$("#hobbyTag").attr("class", classAttr)
		              .attr("title", title)
		              .unbind("click")
		              .on("click",function(){
		            	  myControl.selectHobby(id);
		              }) 
					  .show();
	},

	// 播放
	goPlay : function() {
		if (this.songReady()) {
			this.audio.play();
			var _this = this;
			this.goPlayStyle();
			this.timer = setInterval(function() {
				_this.oTime();
			}, 1000);
			this.start = false;
			this.autoPlay();
			//同步播放歌词
			mPlay();
		}
	},

	// 暂停
	goPause : function() {
		this.audio.pause();
		this.goPauseStyle();
		clearInterval(this.timer);
		this.start = true;
	},

	// 播放样式
	goPlayStyle : function() {
		
		var oLiIndex = $("."+this.prevSongId)[0];
		$(".frmPause").removeClass("frmPause").addClass("frmPlay");
		//alert("goPlayStyle");
		$(oLiIndex).parent()
				   .find(".frmPlay")
				   .addClass("frmPause")
				   .removeClass("frmPlay")
				   .attr("title","暂停");
		         
		this.playBtn.addClass("pause")
		            .removeClass("play")
		            .attr("title","暂停");
	},

	// 暂停样式
	goPauseStyle : function() {
		var oLiIndex = $("."+this.prevSongId)[0];
		$(oLiIndex).parent()
				   .find(".frmPause")
		           .addClass("frmPlay")
		           .removeClass("frmPause")
		           .attr("title","播放");
		this.playBtn.addClass("play")
					.removeClass("pause")
					.attr("播放");
	}
}

//初始化新歌/排行/歌手模块，并绑定事件
function moduleMusic() {
	var aa = {};
	// 模块设置
	var setting = {
		newSong : {
			'target' : 'newSong',
			'type' : '1',
			'firstCount' : 6,
			'count' : 5
		},
		songCharts : {
			'target' : 'songCharts',
			'type' : '1',
			'firstCount' : 6,
			'count' : 5
		},
		singer : {
			'target' : 'singer',
			'type' : '1',
			'firstCount' : 6,
			'count' : 5
		},
		mySong : {
			'target' : 'mySong',
			'type' : '1',
			'firstCount' : 6,
			'count' : 5
		},
		radioStation : {
			'target' : 'radioStation',
			'type' : '1',
			'firstCount' : 9,
			'count' : 2
		}
	};

	// 默认加载新歌模块
	aa.newSong = new Song(setting.newSong);
	// 模块初始化
	$(".menu_tagList li").on('click', function(){
		for ( var i in setting) {
			if ($(this).attr("id") == i) {
				if (typeof aa[i] === 'undefined'){
					aa[i] = new Song(setting[i]);
				} else {
					aa[i].init();
				}
			}
		}
		$(".menu_hover").removeClass("menu_hover");
		$(this).addClass("menu_hover");
	})
	return aa;
};

// 实例化播放器控制台
var myControl = new Control({
	audio : document.getElementById("myMusic"), // 播放器
	playModeNode : $("#modeButton"), // 模式选择按钮
	playBtn : $("#playButton"), // 主控按钮
	playTitle : $("#musicTitle"), // 歌曲TITLE容器
	singerHead : $("#singerHead"), // 歌曲插图容器
	progressWrap : $("#progressWrap"), // 歌曲进度条容器
	progress : $("#progress"), // 歌曲进度条
	oWinObj : $("#oWindow"), // 警告窗容器
	allTimeNode : $("#totleTime"), // 当前时间容器
	currentTimeNode : $("#currentTime")
// 当前时间容器
});

var module = moduleMusic();